﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DcsGauges.Config;
using System.Net.Sockets;
using DcsGauges.Shared.Packets;
using DcsGauges.Shared.Network;

namespace DcsGauges.Network
{
    class ServerChannel : IServerChannel
    {
        private NetworkChannel          networkChannel                      = null;
        
        public ServerChannel(ClientConfigSection config)
        {
            Socket socket                       = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(config.Server.Host, config.Server.Port);
            this.networkChannel                 = new NetworkChannel(socket);

            this.networkChannel.DataPacketReceivedEvent += OnNetworkChannelDataPacketReceivedEvent;

            this.networkChannel.Send(new HandshakePacket(HandshakePacket.ClientTypes.DcsGauges, config.ClientName));
        }

        void OnNetworkChannelDataPacketReceivedEvent(object sender, PacketReceivedEventArgs<DataPacket> e)
        {
            this.FireDataPacketReceived(e.Packet);
        }


        public void Send(Packet packet)
        {
            this.networkChannel.Send(packet);
        }


        private void FireDataPacketReceived(DataPacket packet)
        {
            if (this.DataPacketReceivedEvent != null)
            {
                this.DataPacketReceivedEvent(this, new PacketReceivedEventArgs<DataPacket>(packet));
            }
        }
        
        public event EventHandler<PacketReceivedEventArgs<DataPacket>>  DataPacketReceivedEvent;
    }
}
